package ru.xrm.selenium.applogic2;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.WebDriverException;

import ru.xrm.selenium.applogic.IFilmHelper;
import ru.xrm.selenium.model.FullFilmInfo;
import ru.xrm.selenium.model.ShortFilmInfo;

public class FilmHelper2 extends DriverBasedHelper implements IFilmHelper {

	public FilmHelper2(ApplicationManager2 manager) {
		super(manager.getWebDriver());
	}

	@Override
	public void create(FullFilmInfo film) {
		pages.addNewFilmPage.ensurePageLoaded().setFilmName(film.getName()).setFilmYear(film.getYear()).setFilmNotes(film.getNotes()).clickSubmitButton();
	}

	public int countAddFilmErrors()
	{
		return pages.addNewFilmPage.getCountAddFilmErrors();
	}

	@Override
	public FullFilmInfo getFullFilmInfo()
	{
		return pages.viewFilmInfoPage.getFilmInfo();
	}

	@Override
	public boolean delete(FullFilmInfo filmToDelete) {
		try
		{
			pages.homePage.ensurePageLoaded();
		}
		catch(WebDriverException e)
		{
			pages.internalPage.clickHomePageLink();
		}
		
		List<ShortFilmInfo> filteredShortFilmsInfoList = filterListFilms(filmToDelete, pages.homePage.getShortFilmsListInfo());
		for (ShortFilmInfo filteredFilmInfo : filteredShortFilmsInfoList)
		{
			if(pages.homePage.goToFilmInfo(filteredFilmInfo) != null)
			{
				pages.homePage.goToFilmInfo(filteredFilmInfo);
				if (pages.viewFilmInfoPage.getFilmInfo().equals(filmToDelete))
				{
					pages.viewFilmInfoPage.clickRemoveButton();
					return true;
				}
				pages.viewFilmInfoPage.clickHomePageLink().ensurePageLoaded();
			}
		}
		return false;
	}

	private List<ShortFilmInfo> filterListFilms(FullFilmInfo filmToDelete, List<ShortFilmInfo> shortFilmsInfoList) {
		List<ShortFilmInfo> filteredShortFilmsInfoList = new ArrayList<ShortFilmInfo>();

		for (ShortFilmInfo shortFilmInfo : shortFilmsInfoList)
		{
			if (shortFilmInfo.getName().equals(filmToDelete.getName()))
			{
				filteredShortFilmsInfoList.add(shortFilmInfo);
			}
		}
		return filteredShortFilmsInfoList;
	}


	@Override
	public List<ShortFilmInfo> search(String title) {
		pages.homePage.setSearchLine(title).startSearch();
		return pages.homePage.getShortFilmsListInfo();
	}

}
